package com.shirotest.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyShiroRealm extends AuthorizingRealm {
	/**
	 * 添加用户角色权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		String username = (String) principals.getPrimaryPrincipal();
		
		if("userA".equals(username)) {
			Set<String> roles = new HashSet<String>();
			roles.add("A");
			authorizationInfo.setRoles(roles);
			
			Set<String> permissions = new HashSet<String>();
			permissions.add("A:select");
			permissions.add("A:update");
			authorizationInfo.setStringPermissions(permissions);
		}else if("userB".equals(username)) {
			Set<String> roles = new HashSet<String>();
			roles.add("B");
			authorizationInfo.setRoles(roles);
			
			Set<String> permissions = new HashSet<String>();
			permissions.add("B:select");
			permissions.add("B:update");
			authorizationInfo.setStringPermissions(permissions);
		}
		return authorizationInfo;
	}

	/**
	 * 用户登陆校验
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
		String loginName = (String) authToken.getPrincipal();
		String password = new String((char[]) authToken.getCredentials());
		if("userA".equals(loginName)) {
			if(!"111111".equals(password)) {
				throw new IncorrectCredentialsException();
			}
		}else if("userB".equals(loginName)) {
			if(!"111111".equals(password)) {
				throw new IncorrectCredentialsException();
			}
		}else {
			throw new UnknownAccountException();
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(loginName, "111111", getName());
		return authenticationInfo;
	}
}
